package com.archive.forum.configurer;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;

import java.io.IOException;
import java.util.List;

@EnableWebMvc
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
    @Autowired
    private SessionInterceptor sessionInterceptor;
    @Value("${custom.image-paths}")
    private List<String> imagePaths;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sessionInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login", "/register", "/static/**", "/images/**", "/resources/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 静态资源映射
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");

        registry.addResourceHandler("/resources/**")
                .addResourceLocations("classpath:/resources/");

        // 处理JAR包内外的图片路径
        String externalPath = "file:./src/main/resources/static/images/";  // JAR包外部的相对路径
        String internalPath = "classpath:/static/images/";  // JAR包内部的路径

        // 配置图片路径
        for (String path : imagePaths) {
            registry.addResourceHandler(path)
                    .addResourceLocations(externalPath, internalPath)
                    .setCachePeriod(3600);
        }

        // 上传图片路径
        registry.addResourceHandler("/images/upload/**", "/publish/images/upload/**")
                .addResourceLocations("file:./src/main/resources/static/images/upload/", "classpath:/static/images/upload/")
                .setCachePeriod(3600);

        // 用户相关图片路径
        registry.addResourceHandler("/user/*/images/**", "/user/*/index/images/**")
                .addResourceLocations("file:./src/main/resources/static/images/", "classpath:/static/images/")
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @NotNull
                    @Override
                    protected Resource getResource(@NotNull String resourcePath, @NotNull Resource location) throws IOException {
                        String actualPath = resourcePath.substring(resourcePath.lastIndexOf("/") + 1);
                        return location.createRelative(actualPath);
                    }
                });
    }
}